<script setup>
import {ref,watch,onMounted} from 'vue'
import { queryPageApi,addApi,queryInfoApi,updateApi,deleteApi } from '../../api/clazz';
import { ElMessage,ElMessageBox } from 'element-plus'
import{queryAllApi} from '@/api/emp' 



// 元数据
// 学科列表数据
const subjects = ref([{name:'java',value: 1},{name:'前端',value: 2},{name:'大数据',value: 3},
{name:'Python',value: 4},{name:'Go',value: 5},{name:'嵌入式',value: 6}])
// 班主任列表数据（员工列表）
const empList = ref([])
// 查询员工列表
const getEmpList = async () => { 
  const result = await queryAllApi()
  if(result.code){ 
    empList.value = result.data
  }
}


// 搜索表单对象
const searchClazz = ref( {
  name: '',
  date: [],
  get begin() {
      return this.date?.[0] || ''; // 动态计算 begin
    },
    get end() {
      return this.date?.[1] || ''; // 动态计算 end
    }
})

// 班级列表查询
const clazzList = ref([{}])

// 查询班级列表
const search = async () => {
  const result = await queryPageApi(searchClazz.value.name,searchClazz.value.begin,searchClazz.value.end,
  currentPage.value,pageSize.value)
  if(result.code){
    clazzList.value = result.data.rows
    total.value = result.data.total
  }
}

// 清空查询条件
const clear = () => {
  searchClazz.value = {
    name: '',
    date: [],
    get begin() {
      return this.date?.[0] || ''; // 动态计算 begin
    },
    get end() {
      return this.date?.[1] || ''; // 动态计算 end
    }
  }
  search()
}

// 钩子函数
onMounted(() => {
  search()
  getEmpList()
})

// 分页
const currentPage = ref(1)//页码
const pageSize = ref(10)//每页展示记录数
const background = ref(true)//背景颜色
const total = ref(0)//总记录数

// 每页展示记录数变化
const handleSizeChange = (val) => {
  search()
}
// 页码变化时触发
const handleCurrentChange = (val) => {
  search()
}

// 新增/修改表单
const clazz =ref({
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: '',
  subject: '',
})

// Dialog对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增班级')
// 新增班级按钮
const addClazz = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增班级'
  clazz.value = {name: '',room: '',beginDate: '',endDate: '',masterId: '',subject: ''}
  // 重置表单的校验规则-提示信息
if(clazzFormRef.value){
  clazzFormRef.value.resetFields()
}
}

// 保存按钮
const save = async () => {
  if(!clazzFormRef.value){
    return
  }
   clazzFormRef.value.validate(async (valid) => {
    if(valid){//通过 校验通过
      let result
      if(clazz.value.id){//修改
        result = await updateApi(clazz.value)
      }else{//新增
        result = await addApi(clazz.value)
      }

      if(result.code){ //成功
        //1. 提示消息
        ElMessage.success('保存成功')
        //2. 关闭对话框
        dialogVisible.value = false
        //3. 查询
        search()
      }
      else{//失败
        ElMessage.error(result.msg)
      }
    }else{//不通过
      ElMessage.error('表单校验不通过')
    }
  })
}

// 表单校验
const clazzFormRef = ref()
const rules = ref({
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
  ],
  room: [
    { required: true, message: '请输入班级教室', trigger: 'blur' },
  ],
  beginDate: [
    { required: true, message: '请输入开课时间', trigger: 'blur' },
  ],
  endDate: [
    { required: true, message: '请输入结课时间', trigger: 'blur' },
  ],
  subject: [
    { required: true, message: '请选择学科', trigger: 'blur' },
  ]
})

// 班级编辑按钮
const edit = async (id) => {
  dialogVisible.value = true
  dialogTitle.value = '修改班级'
  const result = await queryInfoApi(id)
  if(result.code){
    clazz.value = result.data
  }
  
  // 重置表单的校验规则-提示信息
if(clazzFormRef.value){
  clazzFormRef.value.resetFields()
}
}

// 班级删除按钮
const deleteById = async (id) => {
  ElMessageBox.confirm('您确定要删除该班级吗 ?','提示',
  {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}
  ).then( async () => {//确认
    try {
    const result = await deleteApi(id)
    if(result.code){
      ElMessage.success('删除成功')
      search()
    }
    else{
      ElMessage.error(result.msg)
    }
    }catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {//取消
    ElMessage.info('您已取消删除')
  })
}

</script>

<template>
   <h1>班级管理</h1>
  <!-- 搜索栏 -->
   <div class="container">
    <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
    <el-form-item label="班级名称">
      <el-input v-model="searchClazz.name" placeholder="请输入班级名称" clearable />
    </el-form-item>
    <el-form-item label="结课时间">
      <el-date-picker
        v-model="searchClazz.date" type="daterange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" 
        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
   </div>

   <!-- 功能按钮 -->
  <div class="container">
    <el-form-item>
      <el-button type="primary" @click="addClazz"> + 新增班级</el-button>
    </el-form-item>
  </div>

   <!-- 班级列表 -->
  <div class="container">
    <el-table :data="clazzList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="index" width="60" label="序号" />
    <el-table-column prop="name" label="班级名称" width="200" align = "center" />
    <el-table-column prop="room" label="班级教室" width="120" align = "center" />
    <el-table-column prop="masterName" label="班主任" width="120" align = "center" />
    <el-table-column prop="beginDate" label="开课时间" width="150" align = "center" />
    <el-table-column prop="endDate" label="结课时间" width="150" align = "center" />
    <el-table-column prop="status" label="状态" width="90" align = "center" />
    <el-table-column prop="updateTime" label="最后操作时间" width="160" align = "center" />
    <el-table-column prop="address" label="操作"  align = "center" >
      <template #default="scope"> 
        <el-button size="small" type="primary" @click="edit(scope.row.id)"><el-icon><Edit /></el-icon>编辑</el-button>
        <el-button size="small" type="danger" @click="deleteById(scope.row.id)"><el-icon><Delete /></el-icon>删除</el-button>
      </template>
    </el-table-column>
    </el-table>
  </div>

  <!-- 分页条 -->
  <div class="container">
    <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[5,10, 20, 30, 40, 50,75,100]"
    :background="background"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  </div>

  <!-- 新增班级/修改班级Dialog对话框 -->
<el-dialog v-model="dialogVisible" :title="dialogTitle" >
    <el-form :model="clazz" label-width="80px" :rules="rules" ref="clazzFormRef" class="dialog-form-item" >
      <!-- 第一行 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="班级名称" prop="name" >
            <el-input v-model="clazz.name"  placeholder="请输入班级名称，如：西安黑马JavaEE就业100期" clearable/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第二行 --> 
       <el-row >
        <el-col :span="24">
          <el-form-item label="班级教室" prop="room" >
            <el-input v-model="clazz.room"  placeholder="请填写班级教室" clearable/>
           </el-form-item>
        </el-col>
      </el-row>
      <!-- 第三行 -->
       <el-row >
        <el-col :span="24">
          <el-form-item label="开课时间" prop="beginDate">
            <el-date-picker v-model="clazz.beginDate" type="date" placeholder="请选择开课时间" 
            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第四行 -->
       <el-row >
        <el-col :span="24">
          <el-form-item label="结课时间" prop="endDate">
            <el-date-picker v-model="clazz.endDate" type="date" placeholder="请选择结课时间"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行 -->
       <el-row >
        <el-col :span="24">
          <el-form-item label="班主任" prop="masterId">
            <el-select v-model="clazz.masterId"  placeholder="请选择班主任姓名" clearable>
              <el-option v-for="master in empList" :key="master.id"  :label="master.name" :value="master.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第六行 -->
       <el-row >
        <el-col :span="24">
          <el-form-item label="学科" prop="subject">
            <el-select v-model="clazz.subject" placeholder="请选择学科" clearable>
              <el-option v-for="subject in subjects" :key="subject.value" :label="subject.name" :value="subject.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="info" @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
</el-dialog>


</template>

<style scoped>
.container {
  margin: 10px 0px;
}

/* 统一表单项左侧间距 */
.dialog-form-item {
margin-left: 20px;
}

/* 输入框/选择框统一宽度 */
.dialog-form-item :deep(.el-input),
.dialog-form-item :deep(.el-select),
.dialog-form-item :deep(.el-date-editor) {
width: 90%;
}
</style>